/*
 * TimeIncrementEvolutiveStrategy.cpp
 *
 *  Created on: 02/10/2011
 *      Author: godinho
 */

#include <evolutive/TimeIncrementEvolutiveStrategy.h>
#include <evolutive/EvolutiveCaseGenerator.h>
#include <evolutive/EvolutiveCaseGeneratorBuilder.h>
#include <evolutive/RandomCaseGen.h>
#include <evolutive/Context.h>
#include <vector>

TimeIncrementEvolutiveStrategy::TimeIncrementEvolutiveStrategy() {
	mEvolutiveAlgorithm = 0;
}

TimeIncrementEvolutiveStrategy::~TimeIncrementEvolutiveStrategy() {
	// TODO Auto-generated destructor stub
}

Case* TimeIncrementEvolutiveStrategy::run(LocalView* lv, int phaseId) {

	//TODO case based mechanism
	//Select initial population
	RandomCaseGen randomGen;
	std::vector<Case*> initialPopulation;
	Case* aux;
	for(int i = 0; i < 10; i++) {
		aux = randomGen.generate();
		initialPopulation.push_back(aux);
	}

	//Setup evolutive generator
	Context context;
	EvolutiveCaseGeneratorBuilder builder(&context);
	mEvolutiveAlgorithm = builder.buildEvolutiveCaseGenerator();

	mEvolutiveAlgorithm->startEvolution(initialPopulation);

	//Select case
	std::vector<Case*> resultCases = mEvolutiveAlgorithm->getCases();

	std::vector<Case*>::iterator casesIt;
	Case* bestCase = (*resultCases.begin());
	for(casesIt = resultCases.begin()+1; casesIt != resultCases.end(); casesIt++) {
		if( (*casesIt)->getFitness() > bestCase->getFitness() ) {
			bestCase = (*casesIt);
		}
	}

	//TODO store cases

	delete mEvolutiveAlgorithm;

	return bestCase;
}

void TimeIncrementEvolutiveStrategy::onStop() {
	if(mEvolutiveAlgorithm != 0) {
		mEvolutiveAlgorithm->setTimedOut();
	}

	//Release case Recycler
	CaseRecycler::releaseRecycler();
}
